package com.mall.service.marketing.aop;

import com.alibaba.fastjson.JSON;
import com.mall.autoconfig.interceptor.BaseContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 日志切面
 */
@Aspect
@Component
public class MallLogAdvice {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Pointcut("@annotation(com.mall.service.marketing.aop.MallLog)")
    public void MallLogAnnotation() {}

    @Around("MallLogAnnotation() && @annotation(mallLog)")
    public Object around(ProceedingJoinPoint joinPoint, MallLog mallLog) throws Throwable {
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();

        String currentId = BaseContext.getCurrentId();
        Signature signature = joinPoint.getSignature();
        // 方法package路径
        String methodUrl = signature.getDeclaringTypeName();
        // 方法名，不包含package路径
        String method = signature.getName();

        //接口耗时
        long time = end - start;
        //获取注解上定义的超时时间
        long timeout = mallLog.timeout();
        Integer isTimeout = 0;
        if (time > timeout) {
            isTimeout = 1;
        }
        //发送到MQ
        Map map = new HashMap();
        map.put("userId", currentId);
        map.put("methodUrl", methodUrl);
        map.put("method", method);
        map.put("time", time);
        map.put("currentTime", currentTime);
        map.put("isTimeout", isTimeout);
        String message = JSON.toJSONString(map);
        amqpTemplate.convertAndSend("mall.log.exchange", "log."+method, message);

        System.out.println("当前用户"+currentId + "," + currentTime+ "，执行了路径为："+methodUrl + "的"+method +"方法" + "，接口耗时" +(end - start) + "毫秒");
        return proceed;
    }
}
